package com.hg.service.impl;


import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.hg.common.HttpStatus;
import com.hg.exception.ServiceException;
import com.hg.mapper.HgUserMapper;
import com.hg.mapper.RoleMapper;
import com.hg.mapper.RoleMenuMapper;
import com.hg.pojo.HgUser;
import com.hg.pojo.Menu;
import com.hg.pojo.dto.HgUserDTO;
import com.hg.pojo.dto.PageDTO;
import com.hg.service.HgUserService;
import com.hg.service.IMenuService;
import com.hg.utiles.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

@Service
public class HgUserServiceImpl extends ServiceImpl<HgUserMapper, HgUser> implements HgUserService {

    @Resource
    private RoleMapper roleMapper;

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Resource
    private IMenuService menuService;

    @Autowired
    private RedisTemplate redisTemplate;
    @Override
    public HgUserDTO login(HgUserDTO hgUserDTO) {

        //从redis取出验证码
        String captcha = (String) redisTemplate.opsForValue().get("captcha");
        //进行验证码比对
        if (!captcha.equals(hgUserDTO.getCode())){
            throw new ServiceException(HttpStatus.CODE_ERROR,"验证码错误");
        }
        String password = hgUserDTO.getPassword();

        //1、将页面提交的密码password进行md5加密处理
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        //2、根据页面提交的用户名username查询数据库
        LambdaQueryWrapper<HgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HgUser::getUsername, hgUserDTO.getUsername());
        HgUser user = this.getOne(queryWrapper);
        //3、如果没有查询到则返回登录失败结果
        if (user == null){
           /* return R.error(HttpStatus.LOGIN_ERROR,"登录失败");*/
            return null;
        }
        // 设置token
        String token = TokenUtils.genToken(user.getId().toString(), user.getPassword());
        user.setToken(token);
        //4、密码比对，如果不一致则返回登录失败结果
        if (!user.getPassword().equals(password)){
           /* return R.error(HttpStatus.LOGIN_ERROR,"登录失败");*/
            return null;
        }
        BeanUtil.copyProperties(user, hgUserDTO, true);

        String role = user.getRole(); // ROLE_ADMIN
        // 设置用户的菜单列表
        List<Menu> roleMenus = getRoleMenus(role);
        hgUserDTO.setMenus(roleMenus);
        return hgUserDTO;
    }

    @Override
    public com.baomidou.mybatisplus.extension.plugins.pagination.Page<HgUser> UserPage(PageDTO pageDTO) {
        int pageSize = pageDTO.getPageSize();
        int currentPage = pageDTO.getCurrentPage();

        //开启分页
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HgUser> pageInfo = new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(currentPage,pageSize);
        //条件构造器
        LambdaQueryWrapper<HgUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(HgUser::getIsDelete,0);
        queryWrapper.like(pageDTO.getUsername() != null,HgUser::getUsername,pageDTO.getUsername());
        queryWrapper.like(pageDTO.getSex() != null,HgUser::getSex,pageDTO.getSex());

        //执行查询
        com.baomidou.mybatisplus.extension.plugins.pagination.Page<HgUser> hgUserPage = this.page(pageInfo, queryWrapper);

        return pageInfo;
    }

    /**
     * 获取当前角色的菜单列表
     * @param roleFlag
     * @return
     */
    private List<Menu> getRoleMenus(String roleFlag) {
        Integer roleId = roleMapper.selectByFlag(roleFlag);
        // 当前角色的所有菜单id集合
        List<Integer> menuIds = roleMenuMapper.selectByRoleId(roleId);

        // 查出系统所有的菜单(树形)
        List<Menu> menus = menuService.findMenus("");
        // new一个最后筛选完成之后的list
        List<Menu> roleMenus = new ArrayList<>();
        // 筛选当前用户角色的菜单
        for (Menu menu : menus) {
            if (menuIds.contains(menu.getId())) {
                roleMenus.add(menu);
            }
            List<Menu> children = menu.getChildren();
            // removeIf()  移除 children 里面不在 menuIds集合中的 元素
            children.removeIf(child -> !menuIds.contains(child.getId()));
        }
        return roleMenus;
    }
}
